package com.learn.jvm;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

public class DynamicMethodTest {

    public static void main(String[] args) {
        //获取类池
        ClassPool classPool = ClassPool.getDefault();
        CtClass ctClass = null;
        try {
            //获取类
            ctClass = classPool.getCtClass("com.learn.jvm.User");
            //获取方法
            CtMethod getUsernameMethod = ctClass.getDeclaredMethod("getUsername");
            //设置新的代码
            getUsernameMethod.setBody("return \"dynamic modified your code ,old result: \" + username;");
            //写入
            ctClass.writeFile();
            //加载该类的字节码（不能少）
            ctClass.toClass();
            //测试使用被修改后的类
            Class userClass = ctClass.toClass();
            User user = (User) userClass.newInstance();
            user.setUsername("小明");
            System.out.println(user.getUsername());

            //换一种方法使用
            /*User user1 = new User("小红");
            System.out.println(user1.getUsername());*/
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
